package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

/*@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public List<Book> findall() {
        return bookService.findall();
    }

    @GetMapping("/{id}")
    public Book findall(Integer id) {
        return bookService.findbyid(id);
    }

    @PostMapping
    public boolean insert(@RequestBody Book book) {
        return bookService.insert(book);
    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

}*/
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result findall() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败，请重试！";
        return new Result(code,bookList,msg);
    }
    /*public Result getAll() {
        List<Book> all = bookService.getAll();
        return new Result(Code.GET_OK, all, "查询成功");
    }*/


    @GetMapping("/{id}")
    public Result getbyid(@PathVariable Integer id) {

        /*if (id == 1) {
            int i = 1 / 0;
        } else if (id == 2) {
            throw new BusinessException(Code.BUSINESS_ERR,"请不要用你的技术挑战我的耐心");
        } else if (id == 3) {
            throw new SystemException(Code.SYSTEM_ERR,"网络堵塞,请稍后再试");
        }*/
        Book book = bookService.findbyid(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败，请重试！";
        return new Result(code,book,msg);
    }

    @PostMapping
    public Result insert(@RequestBody Book book) {
        boolean flag = bookService.insert(book);
        return new Result(flag ? Code.INSERT_OK : Code.INSERT_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean delete = bookService.delete(id);
        return new Result(delete ? Code.DELETE_OK : Code.DELETE_ERR, delete);
    }

}
